import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { MenuItem, TreeNode, AutoComplete, Message } from 'primeng/primeng';
import { MdlSnackbarService } from '@angular-mdl/core';
import { flyIn } from '../../common/animation/common.animation';
import { ResourceService } from '../resource/service/resource.service';
import { RoleService } from './service/role.service';

@Component({
    selector: 'role-resources',
    templateUrl: './role-resources.component.html',
    styleUrls: ['./role-resources.component.scss'],
    providers: [ResourceService, RoleService],
    animations: [flyIn]
})
export class RoleResourcesComponent implements OnInit {
    roleItem: any = {};
    resources: TreeNode[];
    selectedResources: TreeNode[] = new Array<TreeNode>();
    suggestions: TreeNode[];
    suggestion: TreeNode;
    filterStr: string;
    cols: any[] = [{ field: 'rightName', header: '移动端系统权限' }]
    sysRights: any[];
    selectedSysRights: any[] = [];

    @Input()
    set role(role: any) {
        if (!role) return;
        this.roleItem = role;
        this.selectedSysRights = [];
        this.selectedResources = [];
        this.resourceService.getResourceTree().subscribe(data => {
            this.resources = data;
            this.roleService.loadRoleResources(role.roleId).subscribe(roleres => {
                let temp = roleres.resource;
                temp.forEach(e => {
                    if (e.resType == 0) {
                        e['resId'] = 'SYSTEM_' + e['resId'];
                    } else {
                        e['resId'] = 'RES_' + e['resId'];
                    }
                });
                this.recursiveResourceNode(this.resources, temp);
            });
        });
    }
    get role(): any { return this.roleItem; }

    constructor(
        private mdlSnackbarService: MdlSnackbarService,
        private resourceService: ResourceService,
        private roleService: RoleService,
        private route: ActivatedRoute,
        private router: Router) { }

    ngOnInit() {
    }

    /** 岗位资源信息保存事件 */
    save() {
        let params = { 'roleId': this.roleItem.roleId };
        let checkedResources = [];
        this.selectedResources.forEach(ele =>{
            checkedResources.push({ 'resId': ele['id'].split('_')[1], 'resType': ele.data['type'], 'partialSelect': 0 })
        });
        this.recursivePartilSelectedNode(this.resources, checkedResources);
        params['resources'] = checkedResources;
        this.roleService.saveUpdateRoleResources(params).subscribe(data => this.mdlSnackbarService.showToast('数据保存成功！'));
    }

    /** 递归封装所有选中树节点 */
    recursivePartilSelectedNode(resources: TreeNode[], checkedResources: any[]) {
        resources.forEach(element => {
            if (element.children && element.children.length > 0) {
                element.selectable && element.partialSelected &&
                    checkedResources.push({ 'resId': element['id'].split('_')[1], 'resType': element.data['type'], 'partialSelect': 1 });
                this.recursivePartilSelectedNode(element.children, checkedResources);
            } else {
                element.selectable && element.partialSelected &&
                    checkedResources.push({ 'resId': element['id'].split('_')[1], 'resType': element.data['type'], 'partialSelect': 1 });
            }
        });
    }
    /** 资源查找 */
    search(event) {
        this.suggestions = this.getSuggestionRecursive(event.query, this.resources, []);
    }

    /**选择下拉事件 */
    selectSuggestion() {
        this.selectedResources.push(this.suggestion);
        this.recursiveExpandNode(this.resources[0].children, this.suggestion);
    }

    //查找过滤
    getSuggestionRecursive(query: string, nodes: TreeNode[], dest: TreeNode[]) {
        nodes.forEach(node => {
            if (node.children) {
                node.children.forEach(childNode => {
                    if (childNode.label.indexOf(query) != -1) {
                        //dest.push(childNode);
                    }
                });
                this.getSuggestionRecursive(query, node.children, dest);
            }
        });
        return dest;
    }
    /** 递归展开树节点  */
    recursiveExpandNode(nodes: TreeNode[], dest: TreeNode) {
        nodes.forEach(ele => {
            if (dest.data['code'].indexOf(ele.data['code']) != -1) {
                ele.expanded = true;
                this.recursiveExpandNode(ele.children, dest);
            } else {
                ele.expanded = false;
            }
        });
    }
    /** 递归树节点回显已选中资源 */
    recursiveResourceNode(nodes: TreeNode[], roleResources: any[]) {
        nodes.forEach(node => {
            roleResources.forEach(roleres => {
                if (roleres['resType'] == node.data['type']
                    && roleres['resId'] == node['id']) {
                    if (roleres['partialSelect'] == 0) {
                        this.selectedResources.push(node);
                    } else {
                        node.partialSelected = true;
                    }
                }
            });
            this.recursiveResourceNode(node.children, roleResources);
        });
    }
}
